<template>
  <div>
    <div class="user pd" style="margin-bottom:50px;">
      <div class="art-title-box">
        <input type="text" v-model="title" class="art-title" placeholder="成员名称（必须填写）">
      </div>
      <quill-editor ref="myTextEditor"
                    v-model="newsDetail"
                    :options="editorOption">
      </quill-editor>
      <div class="input-group mt">
        <label>IFF职务(原来的成员头衔)：</label>
        <div class="input-group-box"><el-input v-model="member_title" type="textarea" :rows="5" placeholder="输入成员头衔"></el-input></div>
      </div>
      <div class="input-group mt">
        <label>原职务1：</label>
        <div class="input-group-box"><el-input v-model="member_position1" type="textarea" :rows="5" placeholder="输入成员头衔"></el-input></div>
      </div>
      <div class="input-group mt">
        <label>原职务2：</label>
        <div class="input-group-box"><el-input v-model="member_position2" type="textarea" :rows="5" placeholder="输入成员头衔"></el-input></div>
      </div>
      <div class="input-group mt">
        <label>成员简介：</label>
        <div class="input-group-box"><el-input v-model="note" type="textarea" :rows="5" placeholder="输入成员简介（100字以内）"></el-input></div>
      </div>
      <div class="input-group">
        <label>作者：</label>
        <div class="input-group-box"><el-input v-model="author" placeholder="输入作者"></el-input></div>
      </div>
      <div class="input-group">
        <label>来源：</label>
        <div class="input-group-box"><el-input v-model="source" placeholder="输入来源"></el-input></div>
      </div>
      <div class="input-group">
        <label>成员图片：</label>
        <div class="input-group-box cover-box">
          <img :src="cover.url" class="cover" v-if="cover.url!==''">
          <div class="el-upload el-upload--picture-card">
            <i class="el-icon-plus"></i>
            <input type="file" id="cover-img" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" class="zi_upload_input" @change="getfile($event)">
          </div>
          <span class="p-tip">* 建议尺寸190*140</span>
        </div>
      </div>
      <div class="input-group mt">
        <label>分类：</label>
        <div class="input-group-box">
          <el-select v-model="firstLevelCid" placeholder="一级分类" class="cycle-input"  @change="changeFirstLevel">
            <el-option key="" label="请选择一级分类" value=""></el-option>
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="secondLevelCid" placeholder="二级分类" class="cycle-input"  @change="changeSecondLevel">
            <el-option key="" label="请选择二级分类" value=""></el-option>
            <el-option
              v-for="item in secondLevelCategoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="input-group mt">
        <label>所属组织：</label>
        <div class="input-group-box">
          <el-checkbox-group v-model="sourceIds" @change="handleChangeSourceList" size="medium">
            <el-checkbox border v-for="item in sourceList" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <div class="input-group">
        <label>排序：</label>
        <div class="input-group-box"><el-input v-model="sort" placeholder="输入排序值" type="number"></el-input><span style="color: red;">排序值越大越靠前</span></div>
      </div>
      <div class="input-group">
        <label>发布时间：</label>
        <div class="input-group-box">
          <el-date-picker
            v-model="repubTime"
            type="datetime"
            placeholder="请选择发布时间"
            format="yyyy-MM-dd HH:mm:ss"
            default-time="12:00:00">
          </el-date-picker>
        </div>
      </div>
    </div>
    <preview  v-if="isPreview" :priviewObject="priviewObject" v-on:isCloseView="closeView"></preview>
    <div class="bottom-box" v-if="isAdd">
      <el-button type="primary" size="small" @click="publish" :loading="publishLoading"> 立 即 发 布 </el-button>
      <el-button size="small" @click = 'saveAdd' :loading="saveAddLoading"> 保  存 </el-button>
      <el-button @click="showPreview" size="small"> 预  览 </el-button>
    </div>
    <div class="bottom-box" v-else>
      <el-button size="small" @click = 'saveEditor' :loading="saveEditorLoading"> 保 存 修 改 </el-button>
      <el-button @click="showPreview" size="small"> 预  览 </el-button>
    </div>
    <div class="art-fade" v-if="loadPreview">
      <load class="loadfade"></load>
    </div>
  </div>
</template>
<script>
  import api from '../../utils/api'
  import apiConfig from '../../utils/apiconfig'
  import helper from '../../utils/helper'
  import formatdate from '../../utils/formatdate.js'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import { quillEditor } from 'vue-quill-editor'
  import preview from './preview'
  import load from '../../components/loading'
  export default {
    data () {
      return {
        title: '',
        author: '',
        source: '',
        newsDetail: '',
        note: '',
        member_title: '',
        member_position1: '',
        member_position2: '',
        sort: 0,
        cover: {
          url: '',
          img: ''
        },
        isPublished: true,
        pickerOptions0: {
          disabledDate (time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        categoryList: [],
        secondLevelCategoryList: [],
        sourceList: [],
        firstLevelCid: '',
        secondLevelCid: '',
        sourceIds: [],
        repubTime: '',
        type: 2,
        cid: '',
        isTop: 0,
        isRecommend: 0,
        priviewObject: {},
        editorOption: {
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote'],
              // ['blockquote', 'code-block'],
              [{ 'header': 1 }, { 'header': 2 }],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              [{ 'script': 'sub' }, { 'script': 'super' }],
              // [{ 'indent': '-1' }, { 'indent': '+1' }],
              // [{ 'direction': 'rtl' }],
              [{ 'size': ['small', false, 'large', 'huge'] }],
              // [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
              // [{ 'font': [] }],
              [{ 'color': [] }, { 'background': [] }],
              [{ 'align': [] }],
              // ['clean'],
              ['link', 'image', 'video']
            ]
          }
        },
        isPreview: false, // 预览是否出现
        aid: null,
        isAdd: true,
        publishLoading: false,
        saveAddLoading: false,
        saveEditorLoading: false,
        loadPreview: false,
        noteLimit: 600
      }
    },
    components: {
      quillEditor,
      preview,
      load
    },
    created () {
      this.getCategoryLevelOption()
      this.getSourceList()
      var id = this.$route.query.id

      if (id && id !== '' && id !== 'undefined' && id !== null) {
        this.aid = id
        this.isAdd = false
        this.getNewsDetail()
      }
    },
    methods: {
      getfile (event) {
        this.cover.img = event.target.files[0]
        this.cover.url = window.URL.createObjectURL(this.cover.img)
      },
      getCategoryLevelOption () {
        var param = {
          is_video: 2
        }
        api.GET(helper.getManageApiUrl(apiConfig.newsCategoryAllLevel), param, res => {
          this.categoryList = res
        }, res => {
          console.log(res)
        })
      },
      getSourceList () {
        var param = {
          enable: 1
        }
        api.GET(helper.getManageApiUrl(apiConfig.sourceList), param, res => {
          this.sourceList = res
        }, res => {
          console.log(res)
        })
      },
      changeFirstLevel (val) {
        console.log(val)
        this.firstLevelCid = val
        this.categoryList.forEach((item) => {
          if (item.id === val) {
            this.secondLevelCategoryList = item.list
          }
        })
      },
      changeSecondLevel (val) {
        this.secondLevelCid = val
      },
      handleChangeSourceList (value) {
        console.log(this.sourceIds)
        // this.sourceIds = value
        // this.sourceIds = [1, 2, 3, 4]
        // console.log(JSON.stringify(value))
        // console.log(this.sourceIds)
      },
      showPreview () {
        this.priviewObject = {
          title: this.title,
          author: this.author,
          source: this.source,
          newsDetail: this.newsDetail,
          published_time: formatdate(new Date())
        }
        this.isPreview = true
      },
      closeView () {
        this.isPreview = false
      },
      saveArt (status) {
        let formData = new FormData()
        formData.append('title', this.title)
        formData.append('content', this.newsDetail)
        formData.append('author', this.author)
        formData.append('source', this.source)
        formData.append('sort', this.sort)
        formData.append('is_top', this.isTop)
        formData.append('is_recommend', this.isRecommend)
        formData.append('status', status)
        formData.append('type', this.type)
        formData.append('note', this.note)
        formData.append('member_title', this.member_title)
        formData.append('member_position1', this.member_position1)
        formData.append('member_position2', this.member_position2)
        formData.append('first_level_cid', this.firstLevelCid)
        formData.append('second_level_cid', this.secondLevelCid)
        formData.append('cover_path', this.cover.img)
        formData.append('repub_time', helper.formatDateTime(this.repubTime))
        formData.append('source_ids', this.sourceIds.join(','))
        let configs = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        console.log(formData)
        api.POST(helper.getManageApiUrl(apiConfig.addNews), formData, configs, res => {
          var type = '保存'
          if (status === 1) {
            type = '发布'
          }
          this.$notify({
            title: '成功',
            message: type + '成功',
            type: 'success',
            duration: 1500
          })
          this.publishLoading = false
          this.saveAddLoading = false
          this.title = ''
          this.newsDetail = ''
          this.author = ''
          this.source = ''
          this.sort = 0
          this.isTop = 0
          this.isRecommend = 0
          this.note = ''
          this.member_title = ''
          this.member_position1 = ''
          this.member_position2 = ''
          this.firstLevelCid = ''
          this.secondLevelCid = ''
          this.type = 2
          this.sourceIds = []
          this.repubTime = ''
          var cover = document.getElementById('cover-img')
          cover.value = ''
          this.cover.url = ''
          // 直接保存到英文
          api.POST(helper.getManageApiUrl(apiConfig.addNews), formData, configs, res => {
            console.log('save member news to english edition success')
          }, res => {
            console.log('save member news to english edition failed')
          }, true)
        }, res => {
          console.log(res)
        })
      },
      publish () {
//        var title = this.title.replace(/\s/g, '')
//        var note = this.note.replace(/\s/g, '')
        let note = this.note
        let title = this.title
        if (title.length === 0) {
          this.noEmpty('标题不能为空')
          return false
        }
        if (this.newsDetail === '') {
          this.noEmpty('成员内容不能为空')
          return false
        }
        if (note.length === 0 || note.length > this.noteLimit) {
          this.noEmpty('成员简介不能为空且必须' + this.noteLimit + '字以内')
          return false
        }
        if (this.cover.img === '') {
          this.noEmpty('封面图不能为空')
          return false
        }
        if (this.firstLevelCid === '') {
          this.noEmpty('请选择一级分类')
          return false
        }
        if (this.secondLevelCid === '') {
          this.noEmpty('请选择二级分类')
          return false
        }
        this.publishLoading = true
        this.saveArt(1)
      },
      saveAdd () {
//        var title = this.title.replace(/\s/g, '')
//        var note = this.note.replace(/\s/g, '')
        let note = this.note
        let title = this.title
        if (title.length === 0) {
          this.noEmpty('成员名称不能为空')
          return false
        }
        if (this.newsDetail === '') {
          this.noEmpty('成员内容不能为空')
          return false
        }
        if (note.length === 0 || note.length > this.noteLimit) {
          this.noEmpty('成员简介不能为空且必须' + this.noteLimit + '字以内')
          return false
        }

        if (this.cover.img === '') {
          this.noEmpty('封面图不能为空')
          return false
        }
        if (this.firstLevelCid === '') {
          this.noEmpty('请选择一级分类')
          return false
        }
        if (this.secondLevelCid === '') {
          this.noEmpty('请选择二级分类')
          return false
        }
        this.saveAddLoading = true
        this.saveArt(0)
      },
      getNewsDetail () { // 修改成员时，首先获取成员内容
        this.loadPreview = true
        var param = {
          id: this.aid
        }
        api.GET(helper.getManageApiUrl(apiConfig.newsDetail), param, res => {
          var resData = res
          this.firstLevelCid = resData.first_level_cid
          this.secondLevelCid = resData.second_level_cid
          this.title = resData.title
          this.author = resData.author
          this.source = resData.source
          this.sort = resData.sort
          this.isTop = resData.is_top
          this.isRecommend = resData.is_recommend
          this.note = resData.note
          this.member_title = resData.member_title
          this.member_position1 = resData.member_position1
          this.member_position2 = resData.member_position2
          this.type = resData.type
          this.sourceIds = resData.source_ids
          this.newsDetail = resData.content
          this.cover.url = resData.cover_path
          this.cover.img = resData.cover_path
          // 初始话二级分类
          let _this = this
          this.categoryList.forEach((item) => {
            if (item.id === this.firstLevelCid) {
              _this.secondLevelCategoryList = item.list
            }
          })
          // 所有机构的id
          this.sourceIds = resData.source_ids
          this.repubTime = resData.repub_time
          this.loadPreview = false
        }, res => {
          this.noEmpty('获取数据失败')
        })
      },
      saveEditor () {
//        var title = this.title.replace(/\s/g, '')
//        var note = this.note.replace(/\s/g, '')
        let note = this.note
        let title = this.title
        if (title.length === 0) {
          this.noEmpty('标题不能为空')
          return false
        }
        if (this.newsDetail === '') {
          this.noEmpty('成员内容不能为空')
          return false
        }
        if (note.length === 0 || note.length > this.noteLimit) {
          this.noEmpty('成员简介不能为空且必须' + this.noteLimit + '字以内')
          return false
        }
//      if (author.length === 0) {
//        this.noEmpty('成员作者不能为空')
//        return false
//      }
//      if (source.length === 0) {
//        this.noEmpty('成员来源不能为空')
//        return false
//      }
        if (this.cover.img === '') {
          this.noEmpty('封面图不能为空')
          return false
        }
        if (this.firstLevelCid === '') {
          this.noEmpty('请选择一级分类')
          return false
        }
        if (this.secondLevelCid === '') {
          this.noEmpty('请选择二级分类')
          return false
        }
        this.saveEditorLoading = true
        let formData = new FormData()
        formData.append('id', this.aid)
        formData.append('title', this.title)
        formData.append('content', this.newsDetail)
        formData.append('author', this.author)
        formData.append('source', this.source)
        formData.append('sort', this.sort)
        formData.append('is_top', this.isTop)
        formData.append('is_recommend', this.isRecommend)
        formData.append('type', this.type)
        formData.append('note', this.note)
        formData.append('member_title', this.member_title)
        formData.append('member_position1', this.member_position1)
        formData.append('member_position2', this.member_position2)
        formData.append('first_level_cid', this.firstLevelCid)
        formData.append('second_level_cid', this.secondLevelCid)
        formData.append('cover_path', this.cover.img)
        formData.append('source_ids', this.sourceIds.join(','))
        formData.append('repub_time', helper.formatDateTime(this.repubTime))
        let configs = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        api.POST(helper.getManageApiUrl(apiConfig.updateNews), formData, configs, res => {
          this.$notify({
            title: '成功',
            message: '修改已保存',
            type: 'success',
            duration: 1500
          })
          this.saveEditorLoading = false
          // this.$router.push('/index/news/list/51')
          window.history.go(-1)
        }, res => {
          this.noEmpty(res.msg)
        })
      },
      noEmpty (tip) {
        this.$notify({
          title: '提示',
          message: tip,
          type: 'error',
          duration: 1500
        })
      }
    }
  }
</script>
<style>
  .art-fade {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 99;
    background: rgba(255, 255, 255, 0.7);
    padding-top: 5%;
  }
  .quill-editor .ql-container {
    height: 480px;
    line-height: 1.7;
  }
  .quill-editor .ql-container p, .quill-editor .ql-container h1, .quill-editor .ql-container h2{
    padding: 6px 0;
  }
  .quill-editor .ql-container li {
    padding: 3px 0;
  }
  .quill-editor .ql-container ul, .quill-editor .ql-container ol {
    padding: 6px 0;
  }
  .ql-snow.ql-container .ql-editor pre {
    margin-bottom: 6px;
    margin-top: 6px;
    padding: 8px 15px;
  }
  .ql-snow.ql-container .ql-editor blockquote {
    border-left: 4px solid #ccc;
    margin-bottom: 8px;
    margin-top: 8px;
    padding: 5px 16px;
  }
  .input-group-box .el-upload--picture-card {
    position: relative;
    width: 100px;
    height: 100px;
  }
  .input-group-box img.cover {
    width: 95px;
    height: 71px;
    display: block;
    margin-bottom: 10px;
  }
  .input-group-box .el-upload--picture-card i {
    position: absolute;
    top: 35px;
    left: 35px;
  }
  .el-upload--picture-card .zi_upload_input {
    position: absolute;
    display: inline-block;
    width: 100%;
    height: 100%;
    opacity: 0;
    top: 0;
    left: 0;
    cursor: pointer;
  }
  .input-group .input-group-box label.el-switch {
    width: auto;
    line-height: auto;
    margin-top: 7px;
    vertical-align: top
  }
  .art-title-box {
    margin-bottom: 8px;
    padding: 0px 25px;
  }
  .art-title{
    width: 100%;
    border: none;
    background-color: transparent;
    color: #000;
    font-size: 22px;
    height: 45px;
    line-height: 45px;
  }
  .input-group.mt {
    margin-top: 24px;
  }
  .bottom-box {
    position: fixed;
    bottom: 0;
    box-sizing: border-box;
    width: 100%;
    left: 180px;
    background: #f2f2f2;
    border-top: 1px solid #dedede;
    height: 50px;
    text-align: right;
    line-height: 50px;
    padding-right: 350px;
  }
  .bottom-box .el-button {
    margin-left: 25px;
  }
  .cover-box .p-tip {
    display: inline-block;
    color: red;
    font-size: 12px;
    margin-top: 80px;
    margin-left: 10px;
  }
  .input-group .input-group-box label{
    width: auto;
  }
</style>
